// ============================================================================
// 账号管理页面
// ============================================================================

import React, { useState, useEffect } from 'react'
import { WeiboLoginData } from '../../shared/types'
import { accountService } from '../services'
import { useNotifications } from '../hooks/use-notifications'
import { LoadingSpinner } from '../components/ui/loading-spinner'

/**
 * 账号管理页面组件
 */
export function AccountManagePage() {
  const [accounts, setAccounts] = useState<WeiboLoginData[]>([])
  const [loading, setLoading] = useState(true)
  const [validating, setValidating] = useState<number | null>(null)
  const [deleting, setDeleting] = useState<number | null>(null)
  const { showNotification } = useNotifications()

  // 加载账号列表
  const loadAccounts = async () => {
    try {
      setLoading(true)
      const accountList = await accountService.getAccounts()
      console.log(accountList)
      setAccounts(accountList)
    } catch (error) {
      showNotification({
        type: 'error',
        title: '加载失败',
        message: '无法加载账号列表'
      })
    } finally {
      setLoading(false)
    }
  }

  // 开始登录
  const handleStartLogin = async () => {
    try {
      await accountService.startLogin()
      showNotification({
        type: 'success',
        title: '登录成功',
        message: '账号已成功添加',
        duration: 1000 * 3
      })
      await loadAccounts()
    } catch (error) {
      showNotification({
        type: 'error',
        title: '登录失败',
        message: '请重试或检查网络连接',
        duration: 1000 * 3
      })
    }
  }

  // 验证账号
  const handleValidateAccount = async (accountId: number) => {
    try {
      setValidating(accountId)
      const result = await accountService.validateAccountWithDetails(String(accountId))
      showNotification({
        type: result.isValid ? 'success' : 'warning',
        title: result.isValid ? '验证成功' : '验证失败',
        message: result.isValid ? '账号状态正常' : (result.reason || '账号可能已失效'),
        duration: 1000 * 2
      })
      await loadAccounts()
    } catch (error) {
      showNotification({
        type: 'error',
        title: '验证失败',
        message: '无法验证账号状态'
      })
    } finally {
      setValidating(null)
    }
  }

  // 删除账号
  const handleDeleteAccount = async (accountId: number) => {
    if (!confirm('确定要删除这个账号吗？')) {
      return
    }

    try {
      setDeleting(accountId)
      await accountService.deleteAccount(String(accountId))
      showNotification({
        type: 'success',
        title: '删除成功',
        message: '账号已被删除'
      })
      await loadAccounts()
    } catch (error) {
      showNotification({
        type: 'error',
        title: '删除失败',
        message: '无法删除账号'
      })
    } finally {
      setDeleting(null)
    }
  }

  // 删除无效账号
  const handleDeleteInvalidAccounts = async () => {
    if (!confirm('确定要删除所有无效账号吗？')) {
      return
    }

    try {
      const deletedCount = await accountService.deleteInvalidAccounts()
      showNotification({
        type: 'success',
        title: '清理完成',
        message: `已删除 ${deletedCount} 个无效账号`
      })
      await loadAccounts()
    } catch (error) {
      showNotification({
        type: 'error',
        title: '清理失败',
        message: '无法删除无效账号'
      })
    }
  }

  // 格式化时间
  const formatTime = (timestamp: number) => {
    return new Date(timestamp).toLocaleString('zh-CN')
  }

  // 组件挂载时加载数据
  useEffect(() => {
    loadAccounts()
  }, [])

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <LoadingSpinner />
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* 操作按钮 */}
      <div className="flex items-center justify-end">
        <div className="flex space-x-3">
          <button
            onClick={handleDeleteInvalidAccounts}
            className="btn btn-danger"
            disabled={accounts.length === 0}
          >
            清理无效账号
          </button>
          <button
            onClick={handleStartLogin}
            className="btn btn-primary"
          >
            添加账号
          </button>
        </div>
      </div>

      {/* 账号统计 */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
        <div className="bg-white dark:bg-gray-800 rounded-lg p-6 shadow-sm">
          <div className="flex items-center">
            <div className="p-2 bg-blue-100 dark:bg-blue-900 rounded-lg">
              <svg className="w-6 h-6 text-blue-600 dark:text-blue-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
              </svg>
            </div>
            <div className="ml-4">
              <p className="text-sm font-medium text-gray-600 dark:text-gray-400">总账号数</p>
              <p className="text-2xl font-semibold text-gray-900 dark:text-white">{accounts.length}</p>
            </div>
          </div>
        </div>

        <div className="bg-white dark:bg-gray-800 rounded-lg p-6 shadow-sm">
          <div className="flex items-center">
            <div className="p-2 bg-green-100 dark:bg-green-900 rounded-lg">
              <svg className="w-6 h-6 text-green-600 dark:text-green-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
            </div>
            <div className="ml-4">
              <p className="text-sm font-medium text-gray-600 dark:text-gray-400">有效账号</p>
              <p className="text-2xl font-semibold text-gray-900 dark:text-white">
                {accounts.filter(account => account.isValid).length}
              </p>
            </div>
          </div>
        </div>

        <div className="bg-white dark:bg-gray-800 rounded-lg p-6 shadow-sm">
          <div className="flex items-center">
            <div className="p-2 bg-red-100 dark:bg-red-900 rounded-lg">
              <svg className="w-6 h-6 text-red-600 dark:text-red-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z" />
              </svg>
            </div>
            <div className="ml-4">
              <p className="text-sm font-medium text-gray-600 dark:text-gray-400">无效账号</p>
              <p className="text-2xl font-semibold text-gray-900 dark:text-white">
                {accounts.filter(account => !account.isValid).length}
              </p>
            </div>
          </div>
        </div>
      </div>

      {/* 账号列表 */}
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow-sm">
        <div className="px-6 py-4 border-b border-gray-200 dark:border-gray-700">
          <h2 className="text-lg font-medium text-gray-900 dark:text-white">账号列表</h2>
        </div>
        
        {accounts.length === 0 ? (
          <div className="p-12 text-center">
            <svg className="mx-auto h-12 w-12 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
            </svg>
            <h3 className="mt-2 text-sm font-medium text-gray-900 dark:text-white">暂无账号</h3>
            <p className="mt-1 text-sm text-gray-500 dark:text-gray-400">点击"添加账号"开始添加微博账号</p>
            <div className="mt-6">
              <button
                onClick={handleStartLogin}
                className="btn btn-primary"
              >
                添加账号
              </button>
            </div>
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
              <thead className="bg-gray-50 dark:bg-gray-700">
                <tr>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                    用户信息
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                    状态
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                    添加时间
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                    最后验证
                  </th>
                  <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                    操作
                  </th>
                </tr>
              </thead>
              <tbody className="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
                {accounts.map((account) => (
                  <tr key={account.id} className="hover:bg-gray-50 dark:hover:bg-gray-700">
                    <td className="px-6 py-4 whitespace-nowrap">
                      <div className="flex items-center">
                        <img
                          className="h-10 w-10 rounded-full"
                          src={account.userInfo.avatar_hd}
                          alt={account.userInfo.screen_name}
                        />
                        <div className="ml-4">
                          <div className="text-sm font-medium text-gray-900 dark:text-white">
                            {account.userInfo.screen_name}
                          </div>
                          <div className="text-sm text-gray-500 dark:text-gray-400">
                            UID: {account.userInfo.idstr}
                          </div>
                        </div>
                      </div>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <span className={`inline-flex px-2 py-1 text-xs font-semibold rounded-full ${
                        account.isValid
                          ? 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200'
                          : 'bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200'
                      }`}>
                        {account.isValid ? '有效' : '无效'}
                      </span>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-400">
                      {formatTime(account.timestamp)}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-400">
                      {account.lastValidated ? formatTime(new Date(account.lastValidated).getTime()) : '未验证'}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                      <div className="flex items-center justify-end space-x-2">
                        <button
                          onClick={() => handleValidateAccount(account.id)}
                          disabled={validating === account.id}
                          className="text-blue-600 hover:text-blue-900 dark:text-blue-400 dark:hover:text-blue-300"
                        >
                          {validating === account.id ? '验证中...' : '验证'}
                        </button>
                        <button
                          onClick={() => handleDeleteAccount(account.id)}
                          disabled={deleting === account.id}
                          className="text-red-600 hover:text-red-900 dark:text-red-400 dark:hover:text-red-300"
                        >
                          {deleting === account.id ? '删除中...' : '删除'}
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  )
}
